import {configChange} from "../Config";
// @ts-ignore
import Cookies from "js-cookie";
import {isArray, isObject} from "../utils";

let localDataType: string;

configChange((config: any) => {
    localDataType = config.localDataType;
});


// @ts-ignore
const setItem: Function = (name: string, value: any): void => {
    if (isObject(value) || isArray(value)) {
        value = JSON.stringify(value)
    }
    if (localDataType === "cookie") {
        Cookies.set(name, value);
    } else {
        localStorage.setItem(name, value);
    }
};

// @ts-ignore
const getItem: Function = (name: string): any => {
    let res: any;
    if (localDataType === "cookie") {
        try {
            res = JSON.parse(Cookies.get(name) || "");
        } catch (e) {
            res = Cookies.get(name);
        }
    } else {
        try {
            res = JSON.parse(localStorage.getItem(name) || "");
        } catch (e) {
            res = localStorage.getItem(name);
        }
    }

    return res;
};

// @ts-ignore
const removeItem: Function = (name: string) => {
    if (localDataType === "cookie") {
        Cookies.remove(name);
    } else {
        localStorage.removeItem(name)
    }
};

export {
    setItem,
    getItem,
    removeItem
};

